<?php

namespace app\zyhsapi\controller\v1;

use app\aliyun\controller\AliyunFilterWord;
use app\chat\LiveMessage;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccountReport;
use app\common\cachemodel\ZlcrAstr;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\model\ZyhsConsultAstrData;
use app\zyhsapi\model\ZyhsConsultChatRecord;
use app\zyhsapi\model\ZyhsConsultChatRecordDetails;
use app\zyhsapi\model\ZyhsConsultChatRtcRecord;
use app\zyhsapi\model\ZyhsConsultChatRtcRecordComment;
use app\zyhsapi\model\ZyhsConsultChatRtcRecordFeedback;
use app\zyhsapi\model\ZyhsCoupon;
use app\zyhsapi\model\ZyhsTag;
use app\zyhsapi\model\ZyhsUserCoupon;
use think\Db;
use app\zyhsapi\model\ZyhsVrtualuserComment;
use think\response\Json;

class ConsultInfo extends ZyhsAuth
{
    private $appType1 = 1; // 1=>准有好事 2=>准了APP

    /**
     * 我的咨询列表
     * @return Json
     * @throws \Exception
     */
    public function rtcChatList()
    {
        $data = $this->user ? (new ZyhsConsultChatRtcRecord())->userRtcChat($this->appType1, $this->user['id']) : [];

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 获取评价标签
     * @return Json
     * @throws \Exception
     */
    public function getCommentTag()
    {
        $tagModel = new ZyhsTag();
        $tag = $tagModel->getLevelTag(1, 0);
        $tag = $tagModel->getQuestionAllsResrt($tag);

        return show(config('code.success'), '请求成功', $tag);
    }

    /**
     * 咨询评价
     * @return Json
     * @throws \Exception
     */
    public function comment()
    {
        $chatDetailId = input('id/d', 0);
        $tids = input('tids/s', '');
        $remark = input('remark/s', '');
        if (!$chatDetailId || !$tids)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (mb_strlen($remark) > 60)
        {
            return show(config('code.error'), '评价原因最多60字');
        }
        if ($remark)
        {
            $res = AliyunFilterWord::checkText($remark, 'article_comment');
            //若内容有违规且超过配置的相似比例，则进行隐藏不显示，将标签存入库中
            if ($res)
            {
                return show(0, '评价内容涉嫌' . $res['label']);
            }
        }

        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $nowTimw = $this->request->time();
        $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailId);
        $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
        if (!$chatDetail || $chatDetail['uid'] !== $this->user['id'] || !$rtcId)
        {
            return show(config('code.error'), '咨询信息不存在，评价失败～');
        }
        //个咨询只能评价一次
        $rtcInfo = $consultChatRtcRecordModel->getInfoById($rtcId);
        if (isset($rtcInfo['is_comment']) && $rtcInfo['is_comment'] > 0)
        {
            return show(config('code.error'), '已经评价过了，请勿重复操作～');
        }
        $tidsArr = explode(',', $tids);
        $tagInfoList = (new ZyhsTag())->batchGetInfoByIds($tidsArr);
        if (count($tagInfoList) != count($tidsArr))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $level = 0;
        foreach ($tagInfoList as $item)
        {
            if ($level === 0)
            {
                $level = $item['flag'];
            }
            if ($item['flag'] != $level)
            {
                return show(config('code.error'), '请求异常，请稍后再试～');
            }
        }
        if (in_array($level, [1, 5]) && empty($remark))
        {
            return show(config('code.error'), '评价原因不能为空');
        }
        if ($rtcInfo['status'] !== 4)
        {
            return show(config('code.error'), '咨询状态异常，评价失败');
        }
        // 写入 评价数据
        (new ZyhsConsultChatRtcRecordComment())->saveData([
            'rtc_id' => $rtcId,
            'app_type' => $this->appType1,
            'uid' => $this->user['id'],
            'astr_id' => $rtcInfo['astr_id'],
            'level' => $level,
            'tids' => $tids,
            'comment' => $remark,
            'comment_type' => 1,
            'create_time' => $nowTimw,
        ]);
        // 更新了评价状态
        $consultChatRtcRecordModel->updateData($rtcInfo['id'], $this->appType1, $rtcInfo['uid'], ['is_comment' => 1], 1);
        if ($level !== 3)
        {   // 记录 好评与差评
            $fields = $level > 3 ? 'level5_comment' : 'level1_comment';
            (new ZyhsConsultAstrData())->analysisDataUpdate($rtcInfo['astr_id'], (int)date('YmdH'), [
                $fields => Db::raw("{$fields} + 1"),
            ]);
        }
        // 向咨询师 发送信息
        $astrData = current($consultChatRecordDetailsModel->astrDataListResert([$chatDetail], [], $this->user, $this->appType1));
        $astrData['is_comment'] = 1;    // 已评价
        LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $rtcInfo['astr_id']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
            'msg_type' => 2,
            'app_type' => $this->appType1,
            'uid' => $this->user['id'],
            'msg_data' => $astrData,
        ]);
        //  4星和5星处理 咨询师给用户回消息
        if ($level > 3)
        {
            $zlcr3ConsultChatRecordModel = new ZyhsConsultChatRecord();
            $chatId = $zlcr3ConsultChatRecordModel->getChatIdByAstrId($this->appType1, $this->user['id'], $rtcInfo['astr_id']);
            if (!$chatId)
            {
                $insertData = [
                    'app_type' => $this->appType1,
                    'uid' => $this->user['id'],
                    'astr_id' => $rtcInfo['astr_id'],
                    'last_chat_detail_id' => 0,
                    'last_chat_detail_time' => 0,
                    'create_time' => $nowTimw,
                ];
                // 创建新的会话
                $chatId = $zlcr3ConsultChatRecordModel->SaveData($insertData);
            }
            $consultMsgData = [
                'chat_id' => $chatId,
                'app_type' => $this->appType1,
                'uid' => $this->user['id'],
                'astr_id' => $rtcInfo['astr_id'],
                'type' => 1,    //  1=>APP消息 2=>用户发送消息
                'title' => '',
                'content' => '感谢你的评价及推荐！我会继续努力～', // 提问问题
                'data_type' => 1,   // 1=>普通消息  2=>图片  3=>语音咨询消息
                'extend' => [],  //  语音咨询消息 ｜ 图片信息
                'pid' => 0, // 待更新
                'create_time' => $nowTimw,
            ];
            $resData = $consultChatRecordDetailsModel->SaveData($chatId, $consultMsgData);
            $astrInfo = (new ZlcrAstr())->getInfoById($rtcInfo['astr_id']);
            $userData = current($consultChatRecordDetailsModel->userDataListResert([$resData], $astrInfo, $this->user, $this->appType1));
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ZYHS_UID, 0, $this->user['id']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                'msg_type' => 1,
                'astr_id' => $astrInfo['id'],
                'msg_data' => $userData,
            ]);
            $astrData2 = current($consultChatRecordDetailsModel->astrDataListResert([$resData], $astrInfo, $this->user, $this->appType1));
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $rtcInfo['astr_id']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                'msg_type' => 2,
                'app_type' => $this->appType1,
                'uid' => $this->user['id'],
                'msg_data' => $astrData2,
            ]);
            // 更新用户端 最后咨询信息
            $zlcr3ConsultChatRecordModel->updateData($chatId, [
                'uid' => $this->user['id'],
                'last_chat_detail_id' => $chatDetailId,
                'last_chat_detail_time' => $nowTimw,
                'msg_num' => Db::raw('msg_num + 1'),
            ], $this->appType1);
            // 未读数 +1
            $zlcr3ConsultChatRecordModel->setUserUnreadChatIdMsgNum($this->appType1, $this->user['id'], $chatId, 1, 1);
        }
        // 更新 咨询师 能力分
        if ($level !== 3)
        {
            $commentLevelChangeScoreData = [
                1 => -20,
                2 => -10,
                3 => 0,
                4 => 3,
                5 => 5,
            ];
            $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();
            $consultAccountInfo = $zlcr3ConsultAccountModel->getInfoById($rtcInfo['astr_id']);
            // 更新能力分
            $zlcr3ConsultAccountModel->changeAstrLevelScore($consultAccountInfo, $rtcId, 1, $commentLevelChangeScoreData[$level], 1);
        }
        return show(config('code.success'), '请求成功');
    }

    /**
     * 连线咨询 推荐占星师
     * @return Json
     * @throws \Exception
     */
    public function recommend()
    {
        $chatDetailId = input('id/d', 0);
        $type = input('type/d', 0);

        if (!$chatDetailId || !in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();

        $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailId);
        $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
        if (!$chatDetail || $chatDetail['uid'] !== $this->user['id'] || !$rtcId)
        {
            return show(config('code.error'), '咨询信息不存在，推荐失败～');
        }
        $rtcInfo = $consultChatRtcRecordModel->getInfoById($rtcId);
        if ($rtcInfo['status'] !== 4)
        {
            return show(config('code.error'), '咨询状态异常，推荐失败～');
        }
        if ($rtcInfo['is_recommend'] === 1)
        {
            return show(config('code.success'), '操作成功');
        }

        // 更新了评价状态
        $consultChatRtcRecordModel->updateData($rtcInfo['id'], $this->appType1, $rtcInfo['uid'], ['is_recommend' => $type], 1);

        if ($type === 1)
        {   // 推荐
            $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();
            $consultAccountInfo = $zlcr3ConsultAccountModel->getInfoById($rtcInfo['astr_id']);
            $zlcr3ConsultAccountModel->changeAstrLevelScore($consultAccountInfo, $rtcId, 1, 2, 6);

            (new ZyhsConsultAstrData())->analysisDataUpdate($rtcInfo['astr_id'], (int)date('YmdH'), [
                'recommend_num' => Db::raw('recommend_num + 1'),
            ]);
        }

        return show(config('code.success'), '操作成功');
    }

    /**
     * 咨询详情
     * @return Json
     * @throws \Exception
     */
    public function rtcChatDetail()
    {
        $chatDetailId = input('id/d', 0);
        $type = input('type/d', 0);//1=>完整 2=>精简【弹窗评价页面进入】
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();

        $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailId);
        $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
        if (!$chatDetail || $chatDetail['uid'] !== $this->user['id'] || !$rtcId)
        {
            return show(config('code.error'), '服务异常，咨询信息不存在～');
        }
        $data = (new ZyhsConsultChatRtcRecord())->getInfoById($rtcId);

        $astrInfos = (new ZlcrAstr())->getInfoById($data['astr_id'], ['nickname', 'avatar']);

        $couponInfoData = null;
        if (isset($data['extend']['cid']))
        {
            $userCoupon = (new ZyhsUserCoupon())->getInfoById($data['extend']['cid'], ['c_id']);
            $userCouponAttr = (new ZyhsCoupon())->getInfoById($userCoupon['c_id']);
            $couponInfoData = [
                'title' => '优惠',
                'des' => "满{$userCouponAttr['condition']}分钟，免费{$userCouponAttr['discount']}分钟（优惠券）",
                'type' => 1,
            ];
        }
        // 连线福利【新人福利】
        $rtcBenefits = null;
        if (isset($data['extend']['free_rtc_duration']) && $data['extend']['free_rtc_duration'] > $data['test_duration'])
        {   // 连线福利
            $rtcBenefits = [
                'title' => '连线福利',
                'des' => sprintf("免费%d分钟", (int)($data['extend']['free_rtc_duration'] / 60)),
                'type' => 1,
            ];
        }


        if ($type === 1)
        {
            $comment = $data['is_comment'] ? (new ZyhsConsultChatRtcRecordComment())->getInfoById($data['id'], ['level']) : null;

            $res = [
                'title' => '本次消耗详情',
                'list' => [
                    [
                        'title' => '服务编号',
                        'des' => $data['chat_detail_id'] ?? 0,
                        'type' => 2,
                    ],
                    [
                        'title' => '申请时间',
                        'des' => date('Y-m-d H:i:s', $data['create_time']),
                        'type' => 1,
                    ],
                    [
                        'title' => '咨询师',
                        'des' => $astrInfos['nickname'],
                        'type' => 1,
                    ],
                    [
                        'title' => '咨询师单价',
                        'des' => $data['unit_price'] . '准币/分钟',
                        'type' => 1,
                    ],
                    [
                        'title' => '连线时长',
                        'des' => gmdate("H:i:s", $data['duration']),
                        'type' => 1,
                    ],
                ],
            ];
            if ($couponInfoData)
            {   // 优惠券信息
                $res['list'][] = $couponInfoData;
            }
            if ($rtcBenefits)
            {   // 连线福利
                $res['list'][] = $rtcBenefits;
            }
            $res['list'][] = [
                'title' => '计费时长',
                'des' => ceil($data['eff_duration'] / 60) . '分钟',
                'type' => 1,
            ];
            $res['list'][] = [
                'title' => '连线消耗',
                'des' => $data['coin'] . '准币',
                'type' => 1,
            ];
            if ($data['status'] === 4)
            {   // 正常挂断
                $res['list'][] = [
                    'title' => '评价',
                    'des' => $data['is_comment'] ? $comment['level'] : '前往评价',
                    'type' => $data['is_comment'] ? 3 : 4,
                ];
                if ($data['is_recommend'] === 1)
                {
                    $res['list'][] = [
                        'title' => '推荐',
                        'des' => '已推荐',
                        'type' => 1,
                    ];
                }
            }
        } else
        {
            $res = [
                'title' => '本次消耗详情',
                'list' => [
                    [
                        'title' => '服务编号',
                        'des' => $data['chat_detail_id'] ?? 0,
                        'type' => 2,
                    ],
                    [
                        'title' => '咨询师单价',
                        'des' => $data['unit_price'] . '准币/分钟',
                        'type' => 1,
                    ],
                    [
                        'title' => '连线时长',
                        'des' => gmdate("H:i:s", $data['duration']),
                        'type' => 1,
                    ],
                ],
            ];
            if ($couponInfoData)
            {
                $res['list'][] = $couponInfoData;
            }
            if ($rtcBenefits)
            {   // 连线福利
                $res['list'][] = $rtcBenefits;
            }
            $res['list'][] = [
                'title' => '计费时长',
                'des' => ceil($data['eff_duration'] / 60) . '分钟',
                'type' => 1,
            ];
            $res['list'][] = [
                'title' => '连线消耗',
                'des' => $data['coin'] . '准币',
                'type' => 1,
            ];
        }
        $res['nickname'] = $astrInfos['nickname'];
        $res['avatar'] = $astrInfos['avatar'];

        return show(config('code.success'), '请求成功', $res);
    }

    /**
     * 举报占星师
     * @return Json
     * @throws \Exception
     */
    public function reportAstr()
    {
        $astrId = input('astr_id/d', 0);
        $feedback = input('feedback/s', '');
        $tel = input('phone/s', '');
        if (!$feedback || mb_strlen($feedback) > 60)
        {
            return show(config('code.error'), '举报内容字数60字以内');
        }
        $astrInfo = (new ZlcrAstr())->getInfoById($astrId, ['nickname']);
        if (!$astrInfo)
        {
            return show(config('code.error'), '咨询师不存在');
        }
        (new Zlcr3ConsultAccountReport())->insert([
            'app_type' => 1,    // 1=>准有好事 2=>准了APP
            'uid' => $this->user['id'],
            'astr_id' => $astrId,
            'tel' => $tel,
            'content' => $feedback,
            'create_time' => time(),
        ]);
        return show(config('code.success'), '举报成功');
    }

    /**
     * 咨询记录反馈
     * @return Json
     * @throws \Exception
     */
    public function feedbackRtcChat()
    {
        $chatDetailId = input('id/d', 0);
        $feedback = input('feedback/s', '');
        $tel = input('phone/s', '');
        if (!$feedback || mb_strlen($feedback) > 60)
        {
            return show(config('code.error'), '反馈内容字数60字以内');
        }
        if (empty($tel))
        {
            return show(config('code.error'), '请输入联系方式');
        }
        if (mb_strlen($tel) > 15)
        {
            return show(config('code.error'), '联系方式15字以内');
        }
        if ($chatDetailId)
        {
            $chatDetail = (new ZyhsConsultChatRecordDetails())->getInfoById($chatDetailId);
            $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
            if (!$chatDetail || $chatDetail['uid'] !== $this->user['id'] || !$rtcId)
            {
                return show(config('code.error'), '服务异常，咨询信息不存在～');
            }
            $rtcChat = (new ZyhsConsultChatRtcRecord())->getInfoById($rtcId);
            if (!$rtcChat || $rtcChat['uid'] !== $this->user['id'])
            {
                return show(config('code.error'), '反馈失败');
            }
        }
        (new ZyhsConsultChatRtcRecordFeedback())->insert([
            'status' => 0,
            'uid' => $this->user['id'] ?? 0,
            'astr_id' => $rtcChat['astr_id'] ?? 0,
            'chat_detail_id' => $chatDetailId,
            'tel' => $tel,
            'feedback' => $feedback,
            'create_time' => time(),
        ]);
        return show(config('code.success'), '反馈完成');
    }

    /**
     * 大家都在问
     * @return Json
     * @throws \Exception
     */
    public function askList()
    {
        $askList = (new ZyhsVrtualuserComment())->commentList([]);
        array_multisort(array_column($askList, 'sort'), SORT_DESC, array_column($askList, 'id'), SORT_DESC, $askList);
        $data = [];
        $tagModel = new ZyhsTag();
        foreach ($askList as $value)
        {
            $tags = $tagModel->batchGetInfoByIds($value['tids'], ['tag_name']);
            $data[] = [
                'question' => $value['question'],
                'name' => $value['nickname'],
                'avatar' => $value['avatar'],
                'level' => $value['level'],
                'tags' => array_column($tags, 'tag_name'),
                'content' => $value['content'],
                'time' => date('Y-m-d H:i:s', $value['create_time']),
            ];
        }
        return show(config('code.success'), 'Success.', $data);
    }
}
